package cn.cslg.dao.impl;

import cn.cslg.dao.UserDao;
import cn.cslg.domain.User;
import cn.cslg.util.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {

    @Override
    public boolean login(String username, String password)  {
        String sql = "select * from user where username=? and password=?";
        Connection con = null;
        PreparedStatement pstat = null;
        ResultSet rs = null;
        try {
            con = JDBCUtils.getConnection();
            pstat = con.prepareStatement(sql);
            pstat.setString(1,username);
            pstat.setString(2,password);
            rs = pstat.executeQuery();
            if (rs.next()){
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(con,pstat,rs);
        }
        return false;
    }

    @Override
    public boolean findone(String username) {
        //用户存在返回false
        String sql = "select * from user where username=?";
        Connection con = null;
        PreparedStatement pstat = null;
        ResultSet rs = null;
        try {
            con = JDBCUtils.getConnection();
            pstat = con.prepareStatement(sql);
            pstat.setString(1,username);
            rs = pstat.executeQuery();
            if (rs.next()){
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(con,pstat,rs);
        }
        //用户不存在返回true
        return true;
    }

    @Override
    public void insert(User user) {
        String sql = "insert into user values(?,?,?,?,?)";
        Connection con = null;
        PreparedStatement pstat = null;
        try {
            con = JDBCUtils.getConnection();
            pstat = con.prepareStatement(sql);
            pstat.setString(1,user.getUsername());
            pstat.setString(2,user.getPassword());
            pstat.setString(3,user.getName());
            pstat.setString(4,user.getSex());
            pstat.setString(5,user.getTel());
            pstat.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
